﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NCrawler.Extensions;

namespace ZCrawler
{
    public enum ZXPathType
    {
        OuterHtml,
        InnerHtml,
        InnerText
    }
    public class ZRuleXPath : ZBasicRule
    {
        public ZRuleXPath() { }
        public ZRuleXPath(ZXPathType t,string fn) : base(fn)
        {
            XPathes = new List<string>();
            type = t;
        }
        public void AddXPath(string xpath)
        {
            XPathes.Add(xpath);
        }
        public override string Process(HtmlAgilityPack.HtmlDocument doc)
        {
            if (EOF) return "";
            string result = "";
            try
            {
                switch (type)
                {
                    case ZXPathType.InnerHtml:
                        result = doc.DocumentNode.SelectSingleNode(XPathes[tag]).InnerHtml;
                        break;
                    case ZXPathType.InnerText:
                        result = doc.DocumentNode.SelectSingleNode(XPathes[tag]).InnerText;
                        break;
                    case ZXPathType.OuterHtml:
                        result = doc.DocumentNode.SelectSingleNode(XPathes[tag]).OuterHtml;
                        break;
                }
            }
            catch(Exception)
            {}
            EOF = result.IsNullOrEmpty();
            if (!EOF)
            {
                processors.ForEach(p =>
                    {
                        result = p.Process(result);
                    });
                tag++;
                EOF = tag == XPathes.Count;
                return result.Trim();
            }
            return "";
        }
        public override string Description()
        {
            return "<Rule>{0}</Rule>".FormatWith(XPath);
        }
    }
}
